package com.allwees.bs.c.module.order.context.compute.strategy.saletax;

import com.allwees.bs.c.module.order.context.bo.CouponComputeBo;
import com.allwees.bs.c.module.order.context.bo.CouponComputeItemBo;
import com.allwees.core.common.util.MoneyUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class SaleTaxCalculateStrategy implements SaleTaxStrategy {

    @Value("${system.params.order.sales.taxRate:0}")
    private String taxRate;

    @Override
    public CouponComputeBo strategy(CouponComputeBo bo) {
        String value = this.taxRate;
        if (StringUtils.isBlank(value) || !NumberUtils.isCreatable(value)) {
            return bo;
        }

        bo.getItems().forEach(item -> {
            item.setOriginalAmtSaleTaxSku(MoneyUtil.mul(item.getOriginalAmtSaleTaxSku(), new BigDecimal(value)));
            item.setAmtSaleTax(MoneyUtil.mul(item.getAmtSku(), new BigDecimal(value)));
            item.setAmtSaleTaxSkuAfterAdd(MoneyUtil.mul(item.getAmtSku(), new BigDecimal(value)));
            item.computeAmt();
        });

        bo.setAmtSaleTax(bo.getItems().stream().filter(o -> o.getAmtSaleTax() != null).map(CouponComputeItemBo::getAmtSaleTax).reduce(BigDecimal.ZERO, BigDecimal::add));
        bo.setAmtSaleTaxAfterAdd(bo.getItems().stream().filter(o -> o.getAmtSaleTax() != null).map(CouponComputeItemBo::getAmtSaleTax).reduce(BigDecimal.ZERO, BigDecimal::add));
        return bo.computeAmt();
    }
}
